package com.rujue.qianzhi.server;

import org.apache.thrift.TProcessor;
import org.apache.thrift.protocol.TBinaryProtocol;
import org.apache.thrift.server.THsHaServer;
import org.apache.thrift.server.TServer;
import org.apache.thrift.transport.TNonblockingServerSocket;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.rujue.qianzhi.thrift.HelloImpl;
import com.rujue.qianzhi.thrift.gen.Hello;

@Component
public class ThriftServer {
	private static final Logger logger = LoggerFactory.getLogger(ThriftServer.class);

	@Value("${thrift.port}")
	private int port;
	
	@Value("${thrift.time_out}")
	private int time_out;
	
	@Autowired
	private HelloImpl helloImpl;

	@SuppressWarnings({ "rawtypes", "unchecked" })
	public void start() {
		logger.info("thrift服务,端口号: {}", Integer.valueOf(this.port));
		logger.info("thrift服务,连接时间: {}", Integer.valueOf(this.time_out));
		try {
			TProcessor tprocessor = new Hello.Processor(helloImpl);
			TNonblockingServerSocket tServerSocket = new TNonblockingServerSocket(
					new TNonblockingServerSocket.NonblockingAbstractServerSocketArgs()
							.port(this.port).clientTimeout(time_out));
			THsHaServer.Args tArgs = new THsHaServer.Args(tServerSocket);
			tArgs.processor(tprocessor);
			tArgs.protocolFactory(new TBinaryProtocol.Factory());
			TServer server = new THsHaServer(tArgs);
			logger.info("启动thrift服务,端口号为:{}", Integer.valueOf(this.port));
			server.serve();
		} catch (Exception e) {
			logger.error("thrift服务启动失败", e);
		}
	}
}
